package com.ruoyi.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.goods.domain.*;
import com.ruoyi.goods.mapper.*;
import com.ruoyi.goods.service.ITbGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TbGooodsServiceImpl implements ITbGoodsService {

    @Autowired
    private TbGoodsMapper tbGoodsMapper;

    @Autowired
    private TbGoodsDescMapper tbGoodsDescMapper;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private TbBrandMapper tbBrandMapper;

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Override
    public void save(GoodsEntity goodsEntity) {
        //添加商品表数据
        TbGoods goods = goodsEntity.getGoods();
        //1：待提交
        //2：待审核
        //3：审核通过
        //4：审核驳回
        goods.setAuditStatus("1");
        // 获取自增主键， useGeneratedKeys    <selectKey>
        tbGoodsMapper.insertTbGoods(goods);

        //添加商品描述表数据
        Long goodsId = goods.getId();
        TbGoodsDesc goodsDesc = goodsEntity.getGoodsDesc();
        goodsDesc.setGoodsId(goodsId);
        tbGoodsDescMapper.insertTbGoodsDesc(goodsDesc);


        TbBrand tbBrand = tbBrandMapper.selectTbBrandById(Long.parseLong(goods.getBrandId() + ""));
        String brandName = tbBrand.getBrandName();

        TbItemCat tbItemCat = tbItemCatMapper.selectTbItemCatById(Long.parseLong(goods.getCategory3Id() + ""));

        List<TbItem> item = goodsEntity.getItem();
        for (TbItem tbItem : item) {
            String title = brandName + "  " + goods.getGoodsName();
            String spec = tbItem.getSpec();
            Map map = JSONObject.parseObject(spec, Map.class);
            Collection values = map.values();
            Iterator iterator = values.iterator();
            while (iterator.hasNext()){
                title += " "+iterator.next();

            }
            tbItem.setTitle(title);

            String itemImages = goodsDesc.getItemImages();
            List<Map> images = JSONArray.parseArray(itemImages, Map.class);
            String imageUrl = (String) images.get(0).get("url");
            tbItem.setImage(imageUrl);

            tbItem.setCategoryId(goods.getCategory3Id());

            tbItem.setStatus("0");

            tbItem.setCreateTime(new Date());
            tbItem.setUpdateTime(new Date());

            tbItem.setGoodsId(goodsId);

            tbItem.setSellerId("admin");
            tbItem.setSeller("官方旗舰店");

            tbItem.setCategory(tbItemCat.getName());
            tbItem.setBrand(brandName);

            tbItemMapper.insertTbItem(tbItem);
        }




    }
}
